package net.lzzy.practices.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author liaodcc on 2022/5/15 8:57.
 */
public class FileUtils {
    public static JSONObject upload(MultipartFile file,String dir){
        JSONObject result = new JSONObject();
        try{
            String originName = file.getOriginalFilename();
            String suffix = Objects.requireNonNull(originName).substring(originName.lastIndexOf("."));
            String newName = UUID.randomUUID() + suffix;
            File f = new File(dir + newName);
            file.transferTo(f);
            result.put("url",newName);
            result.put("message","文件上传成功");
            result.put("status",true);
        }catch (IOException e){
            e.printStackTrace();
            result.put("url","");
            result.put("message","上传失败:"+e.getMessage());
            result.put("status",false);
        }
        return result;
    }
}
